|
|
|
|
|
|
|
However, this approach means that if your program uses only one log file, you still have to pass the filename to the procedure each time you call it: |
|
|
|
|
|
|
|
|
LogPrint "C:\LOGFILE.TXT", "Error Opening the file " & sUserFile |
|
|
|
|
|
|
|
|
For this particular procedure, the sLogFile argument probably does not change much throughout the program. However, hard-coding it into the LogPrint procedure does not make much sense either, so a public variable would be the logical choice: |
|
|
|
|
|
|
|
|
Public sLogFileName As String
Sub LogPrint(sMessage As String)
Dim nFileNum As Integer
nFileNum = FreeFile
Open sLogFileName for Append as #nFileNum
Print #nFileNum, Now & " - " & sMessage
Close #nFileNum
End Sub |
|
|
|
|
|
|
|
|
Before calling the procedure, your program needs to set the value of sLogFileName. The Public keyword makes it visible to all the other procedures in your program. The variable nFileNum, on the other hand, can be used only within the LogPrint procedure, as it should be. |
|
|
|
|
|
|
|
|
If you are going to use the variables in a number of procedures and the procedure is specific to the current program, setting up the variables as public variables is the better approach. However, for the sake of reusability among projects, keeping procedures as independent as possible is a good idea. To do so, you should define all the necessary parameters to be passed to the procedure in the Sub statement and pass the parameters in the calling statement. Additionally, all variables used by the procedure should be Private (local) variables that are declared within the procedure itself. |
|
|
|
|
|
|
|
|
The parameters used by a procedure can provide two-way communication between the procedure and the calling program. The procedure can use information in the parameters to perform a calculation and then pass the results back to the calling program in another parameter. |
|
|
|
|
|
|
|
|
For example, the following procedure gets the height and width of a rectangle from the parameters list and then calculates the area and perimeter of the rectangle. These values are returned through the parameters list: |
|
|
|
|
|
|
|
|
Sub CalcRectangle(nWidth as Integer, nHeight as Integer, _
nArea as Integer, nPerimeter as Integer)
nArea = nWidth * nHeight
nPerimeter = 2 * (nWidth + nHeight)
End Sub |
|
|
|
|
|
|
|
|
The procedure can be called by using variables for both the input and output parameters, as follows: |
|
|
|
|
|
|
|
|
nWid = 5
nHgt = 5
nArea = 0
nPerm = 0
CalcRectangle nWid, nHgt, nArea, nPerm |
|
|
|
|
|